package com.jingdianjichi.changerecord.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jingdianjichi.changerecord.entity.ChangeRecord;
import com.jingdianjichi.changerecord.properties.ChangeRecordProperties;
import com.jingdianjichi.changerecord.strategy.DictStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * 默认变更记录实现类，redis存储
 *
 * @author Hu_bx
 * @date 13:23 2023/9/16
 **/
@Slf4j
public class RedisChangeRecordImpl extends AbstractChangeRecordImpl {

    private final StringRedisTemplate redisTemplate;
    private final ChangeRecordProperties changeRecordProperties;


    public RedisChangeRecordImpl(StringRedisTemplate redisTemplate, DictStrategy dictStrategy, ChangeRecordProperties changeRecordProperties) {
        super(dictStrategy);
        this.redisTemplate = redisTemplate;
        this.changeRecordProperties = changeRecordProperties;
    }

    @Override
    public ChangeRecord getById(Object id) {
        String json = redisTemplate.opsForValue().get(changeRecordProperties.getRedisKey() + id);
        if (!JSONUtil.isTypeJSON(json)) {
            return null;
        }
        return JSONUtil.toBean(json, ChangeRecord.class);
    }


    @Override
    public List<String> getDescribe(String id) {
        ChangeRecord changeRecord = getById(id);
        return ObjUtil.isEmpty(changeRecord) || StrUtil.isBlank(changeRecord.getDescribe()) ? CollUtil.toList() : JSONUtil.toList(changeRecord.getDescribe(), String.class);
    }

    @Override
    public void createChangeDescribeCallBack(ChangeRecord changeRecord, Class<?> returnType) {
        redisTemplate.opsForValue().set(changeRecordProperties.getRedisKey() + changeRecord.getId(), JSONUtil.toJsonStr(changeRecord));
    }

    @Override
    public void createChangeRecordCallBack(ChangeRecord changeRecord, Class<?> returnType) {
        redisTemplate.opsForValue().set(changeRecordProperties.getRedisKey() + changeRecord.getId(), JSONUtil.toJsonStr(changeRecord));
    }


}
